package org.cloud.im.server.demo.command;

import org.cloud.im.core.ImChannelContext;
import org.cloud.im.core.ImConst;
import org.cloud.im.core.ImPacket;
import org.cloud.im.core.exception.ImException;
import org.cloud.im.core.http.HttpRequest;
import org.cloud.im.core.packets.Command;
import org.cloud.im.core.packets.LoginReqBody;
import org.cloud.im.core.utils.JsonKit;
import org.cloud.im.server.CloudImServerAPI;
import org.cloud.im.server.command.CommandManager;
import org.cloud.im.server.command.handler.LoginReqHandler;
import org.cloud.im.server.processor.handshake.WsHandshakeProcessor;

/**
 * @Author: w.weidong.lin@abite.com
 * @Description: TODO
 * @Date: create in 2021/10/20 9:17
 */
public class DemoWsHandshakeProcessor extends WsHandshakeProcessor {

    @Override
    public void onAfterHandshake(ImPacket packet, ImChannelContext imChannelContext) throws ImException {
        LoginReqHandler loginHandler = (LoginReqHandler) CommandManager.getCommand(Command.COMMAND_LOGIN_REQ);
        HttpRequest request = (HttpRequest) packet;
        String username = request.getParams().get("username") == null ? null : (String) request.getParams().get("username")[0];
        String password = request.getParams().get("password") == null ? null : (String) request.getParams().get("password")[0];
        String token = request.getParams().get("token") == null ? null : (String) request.getParams().get("token")[0];
        LoginReqBody loginBody = new LoginReqBody(username, password, token);
        byte[] loginBytes = JsonKit.toJsonBytes(loginBody);
        request.setBody(loginBytes);
        try {
            request.setBodyString(new String(loginBytes, ImConst.CHARSET));
        } catch (Exception e) {
            throw new ImException(e);
        }
        ImPacket loginRespPacket = loginHandler.handler(request, imChannelContext);
        if (loginRespPacket != null) {
            CloudImServerAPI.send(imChannelContext, loginRespPacket);
        }
    }
}
